//
//  ESCPrinter.m
//  Saas
//
//  Created by 杨荣 on 2020/6/3.
//  Copyright © 2020 bing. All rights reserved.
//

#import "ESCPrinter.h"
#import "UIImage+Printer.h"
#import "NSString+Print.h"
#import "SACommoditySpecialFeesModel.h"
#import "EscCommand.h"

@implementation ESCPrinter
- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (NSInteger)printerByteWidth {
    return 48;
}

- (NSData *)resetGprinterPrint {
    
    NSMutableData *data = [NSMutableData data];
    Byte byte1[] = {0x1B,0x40};// 初始化打印机
    [data appendBytes:byte1 length:sizeof(byte1)];
    Byte byte2[] = {0x1B,0x32};// 设置行间距为1/6英寸，约34个点
    [data appendBytes:byte2 length:sizeof(byte2)];
    Byte byte3[] = {0x1B,0x4D,0x00};// 设置字体:标准0x00，压缩0x01;
    [data appendBytes:byte3 length:sizeof(byte3)];
    return data;
}

#pragma mark ---------- 基础语法 ----------
#pragma mark 查询打印机
- (NSData *)queryGprinter{
    Byte byte[] = {0x1d,0x49,0x43};
    NSData *data = [[NSData alloc] initWithBytes:byte length:sizeof(byte)];
    return data;
}

#pragma mark 换行
- (NSData *)lineFeed {
    
    NSMutableData *data = [NSMutableData data];
    Byte byte[] = {0x0A};
    [data appendBytes:byte length:sizeof(byte)];
    return data;
}

#pragma mark 文字对齐方式
- (NSData *)setAlignment:(NSTextAlignment)alignment {
    
    NSMutableData *data = [NSMutableData data];
    Byte byte[] = {0x1B,0x61,alignment};
    [data appendBytes:byte length:sizeof(byte)];
    return data;
}

#pragma mark 文字加粗
- (NSData *)setTextBold:(BOOL)bold {
    NSMutableData *data = [NSMutableData data];
    if (bold) {
        Byte byte[] = {0x1b,0x21,0x08};
        [data appendBytes:byte length:sizeof(byte)];
    }else {
        Byte byte[] = {0x1b,0x21,0x00};
        [data appendBytes:byte length:sizeof(byte)];
    }
    return data;
}


#pragma mark 文字大小
- (NSData *)setTextFont:(PrinterPrintTextFont)textFont {
    
    NSMutableData *data = [NSMutableData data];
    
    if (textFont == PrinterPrintTextFontBig) {
        Byte byte[] = {0x1D,0x21,0x22};
        [data appendBytes:byte length:sizeof(byte)];
    }else if (textFont == PrinterPrintTextFontMiddle) {
        Byte byte[] = {0x1D,0x21,0x01};
        [data appendBytes:byte length:sizeof(byte)];
    }else {
        Byte byte[] = {0x1D,0x21,0x00};
        [data appendBytes:byte length:sizeof(byte)];
    }
    return data;
}
- (NSData *)setCenterTextFont:(PrinterPrintTextFont)textFont {
    
    NSMutableData *data = [NSMutableData data];
    
    if (textFont == PrinterPrintTextFontBig) {
        Byte byte[] = {0x1D,0x21,0x22};
        [data appendBytes:byte length:sizeof(byte)];
    }else if (textFont == PrinterPrintTextFontMiddle) {
        Byte byte[] = {0x1D,0x21,0x11};
        [data appendBytes:byte length:sizeof(byte)];
    }else {
        Byte byte[] = {0x1D,0x21,0x00};
        [data appendBytes:byte length:sizeof(byte)];
    }
    return data;
}


#pragma mark 文字内容
- (NSData *)setText:(NSString *)text {
    
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData *data = [text dataUsingEncoding:enc];
    return data;
}

#pragma mark 切纸
- (NSData *)paperCut {
    
    Byte byte[] = {0x1d,0x56,0x00};
    NSData *data =[[NSData alloc] initWithBytes:byte length:sizeof(byte)];
    return data;
}

#pragma mark 打印结尾（留白）
- (NSData *)printFooter {
    
    NSMutableData *data = [NSMutableData data];
    [data appendData:[self lineFeed]];
    [data appendData:[self lineFeed]];
    [data appendData:[self lineFeed]];
    [data appendData:[self lineFeed]];
    [data appendData:[self lineFeed]];
    [data appendData:[self lineFeed]];
    return data;
}

- (NSData *)printImage:(UIImage *)image {
    if (!image) {
        return nil;
    }
    
    NSMutableData *data = [NSMutableData data];
    [data appendData:[self setAlignment:NSTextAlignmentLeft]];
    
    NSData *imageData = [image bitmapData];
    [data appendData:imageData];
    [data appendData:[self lineFeed]];
    
    Byte byte[] = {0x1B,0x32};
    [data appendBytes:byte length:sizeof(byte)];
    return data;
}

- (NSData *)printCenterText:(NSString *)text  font:(PrinterPrintTextFont)font {
    return [self printText:text font:font alignment:(NSTextAlignmentCenter)];
}

- (NSData *)printCenterText2:(NSString *)text  font:(PrinterPrintTextFont)font {
    
    NSString *printName = [kPrint substringToIndex:5];
    if ([printName isEqualToString:@"MHT-P"]) {
        return [self printText:text font:font alignment:(NSTextAlignmentCenter)];
    }
    
    NSString *leftText = @"";
    NSString *rightText = text;
    if (leftText.length <=0) {
        leftText = @"";
    }
    if (rightText.length <= 0) {
        rightText = @"";
    }
    
    // 右边文字
    NSDictionary *rightTextCharacterDic = [rightText characterStatistics];
    NSInteger rightTextCharacterCountForChinese = [[rightTextCharacterDic valueForKey:@"CharacterCountForChinese"] integerValue];// 中文字符个数
    NSInteger rightTextCharacterCountForNotChinese = rightText.length-rightTextCharacterCountForChinese;// 其它非中文字符个数
    
    NSInteger byteUnitForChinese = 2;
    NSInteger byteUnitForNotChinese = 1;
    
    if (font == PrinterPrintTextFontBig) {
        byteUnitForChinese = 6;
        byteUnitForNotChinese = 3;
    }else if (font == PrinterPrintTextFontMiddle) {
        byteUnitForChinese = 2;
        byteUnitForNotChinese = 1.5;
    }else {
        byteUnitForChinese = 2;
        byteUnitForNotChinese = 1;
    }
    
    SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
    NSInteger printerByteWidth = 48;
    if ([overallSetting.printSize.value isEqualToString:@"0"] && [SAValueManger shareInStance].oldPrint != YES) {
        printerByteWidth = 32;
    }
    NSInteger rightTextByteOriginX = (printerByteWidth-rightTextCharacterCountForChinese*byteUnitForChinese-rightTextCharacterCountForNotChinese*byteUnitForNotChinese)/2;
    NSString *printText = [NSString getPrintTextWithTextInfoArray:@[@{leftText:@(0)},@{rightText:@(rightTextByteOriginX)}] font:(NSStringFont)font];
    
    NSData *data = [self printText:printText font:font alignment:(NSTextAlignmentLeft) bold:YES];
    return data;
}

- (NSData *)printText:(NSString *)text font:(PrinterPrintTextFont)font alignment:(NSTextAlignment)alignment {
    
    NSMutableData *data = [NSMutableData data];
    [data appendData:[self setAlignment:alignment]];
    
    if (alignment == NSTextAlignmentCenter) {
        [data appendData:[self setCenterTextFont:font]];
    }else {
        [data appendData:[self setTextFont:font]];
    }
    
    [data appendData:[self setText:text]];
    [data appendData:[self setTextBold:YES]];// 默认不加粗
    [data appendData:[self lineFeed]];
    return data;
}

- (NSData *)noLineprintText:(NSString *)text font:(PrinterPrintTextFont)font alignment:(NSTextAlignment)alignment {
    
    NSMutableData *data = [NSMutableData data];
    [data appendData:[self setAlignment:alignment]];
    [data appendData:[self setTextFont:font]];
    [data appendData:[self setText:text]];
    [data appendData:[self setTextBold:YES]];// 默认不加粗
    return data;
}

- (NSData *)printSamallText:(NSString *)text font:(PrinterPrintTextFont)font alignment:(NSTextAlignment)alignment {
    
    NSMutableData *data = [NSMutableData data];
    [data appendData:[self setAlignment:alignment]];
    
    NSMutableData *data2 = [NSMutableData data];
    Byte byte3[] = {0x1B,0x4D,0x01};// 设置字体:标准0x00，压缩0x01;
    [data2 appendBytes:byte3 length:sizeof(byte3)];

    [data appendData:data2];
    [data appendData:[self setText:text]];
    [data appendData:[self setTextBold:YES]];// 默认不加粗
    [data appendData:[self lineFeed]];
    return data;
}

- (NSData *)noLinePrintSamallText:(NSString *)text font:(PrinterPrintTextFont)font alignment:(NSTextAlignment)alignment {
    
    NSMutableData *data = [NSMutableData data];
    [data appendData:[self setAlignment:alignment]];
    
    NSMutableData *data2 = [NSMutableData data];
    Byte byte3[] = {0x1B,0x4D,0x01};// 设置字体:标准0x00，压缩0x01;
    [data2 appendBytes:byte3 length:sizeof(byte3)];

    [data appendData:data2];
    [data appendData:[self setText:text]];
    [data appendData:[self setTextBold:YES]];// 默认不加粗
    return data;
}

- (NSData *)printLeftText:(NSString *)leftText rightText:(NSString *)rightText font:(PrinterPrintTextFont)font {
    
    if (leftText.length <=0) {
        leftText = @"";
    }
    if (rightText.length <= 0) {
        rightText = @"";
    }
    
    // 右边文字
    NSDictionary *rightTextCharacterDic = [rightText characterStatistics];
    NSInteger rightTextCharacterCountForChinese = [[rightTextCharacterDic valueForKey:@"CharacterCountForChinese"] integerValue];// 中文字符个数
    NSInteger rightTextCharacterCountForNotChinese = rightText.length-rightTextCharacterCountForChinese;// 其它非中文字符个数
    
    NSInteger byteUnitForChinese = 2;
    NSInteger byteUnitForNotChinese = 1;
    
    if (font == PrinterPrintTextFontBig) {
        byteUnitForChinese = 6;
        byteUnitForNotChinese = 3;
    }else if (font == PrinterPrintTextFontMiddle) {
        byteUnitForChinese = 2;
        byteUnitForNotChinese = 1.5;
    }else {
        byteUnitForChinese = 2;
        byteUnitForNotChinese = 1;
    }
    
    SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
    NSInteger printerByteWidth = 48;
    if ([overallSetting.printSize.value isEqualToString:@"0"] && [SAValueManger shareInStance].oldPrint != YES) {
        printerByteWidth = 32;
    }
    NSString *print = kPrint;
    if (print != nil && print.length > 7) {
        NSString *printName = [kPrint substringToIndex:7];
        // 二维码模块大小 1~16
        if ([printName isEqualToString:@"MHT-P58"]) {
            printerByteWidth = 38;
        }
    }
    
    NSInteger rightTextByteOriginX = printerByteWidth-rightTextCharacterCountForChinese*byteUnitForChinese-rightTextCharacterCountForNotChinese*byteUnitForNotChinese;
    NSString *printText = [NSString getPrintTextWithTextInfoArray:@[@{leftText:@(0)},@{rightText:@(rightTextByteOriginX)}] font:(NSStringFont)font];
    
    NSData *data = [self printText:printText font:font alignment:(NSTextAlignmentLeft)];
    return data;
    
}

- (NSData *)printCenterText:(NSString *)text  font:(PrinterPrintTextFont)font bold:(BOOL)bold {
    NSData *data = [self  printCenterText:text font:font];
    if (bold) {
        NSMutableData *allData = [NSMutableData dataWithData:[self setTextBold:bold]];
        [allData appendData:data];
        return allData;
    }else {
        return data;
    }
}
- (NSData *)printText:(NSString *)text font:(PrinterPrintTextFont)font alignment:(NSTextAlignment)alignment bold:(BOOL)bold {
    NSData *data = [self  printText:text font:font alignment:alignment];
    if (bold) {
        NSMutableData *allData = [NSMutableData dataWithData:[self setTextBold:bold]];
        [allData appendData:data];
        return allData;
    }else {
        return data;
    }
}
- (NSData *)printLeftText:(NSString *)leftText rightText:(NSString *)rightText font:(PrinterPrintTextFont)font bold:(BOOL)bold {
    NSData *data = [self  printLeftText:leftText rightText:rightText font:font];
    if (bold) {
        NSMutableData *allData = [NSMutableData dataWithData:[self setTextBold:bold]];
        [allData appendData:data];
        return allData;
    }else {
        return data;
    }
}


- (NSData *)printTextInfoArray:(NSArray <NSDictionary *>*)textInfoArray {
    
    NSString *printText = [NSString getPrintTextWithTextInfoArray:textInfoArray font:((NSStringFont)PrinterPrintTextFontSmall)];
    NSData *data = [self printText:printText font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    return data;
}


- (NSData *)printQRCode:(NSArray <NSDictionary *>*)dataArray {
    
    NSMutableData *data = [NSMutableData data];
    for (NSDictionary *dic in dataArray) {
        NSString *key = dic.allKeys.firstObject;// 二维码名称
        NSString *value = dic.allValues.firstObject;// 二维码信息
        
        NSString *printName = [kPrint substringToIndex:5];
        // 二维码模块大小 1~16
        if ([SAValueManger shareInStance].oldPrint == YES || [printName isEqualToString:@"MHT-P"]) {
            //居中
            [data appendData:[self setAlignment:NSTextAlignmentCenter]];
            Byte byte1[] = {0x1D,0x28,0x6B,0x03,0x00,0x31,0x43,0x06};
            [data appendBytes:byte1 length:sizeof(byte1)];
        }else {

            SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
            if ([kPrint containsString:@"PrinterLE_"]) {
                [data appendData:[self setAlignment:NSTextAlignmentCenter]];
                Byte byte1[] = {0x1D,0x28,0x6B,0x03,0x00,0x31,0x43,0x06};
                [data appendBytes:byte1 length:sizeof(byte1)];
                    
            }else if ([overallSetting.printSize.value isEqualToString:@"1"]) {
                //居中
                [data appendData:[self setAlignment:NSTextAlignmentCenter]];
                Byte byte1[] = {0x1D,0x28,0x6B,0x03,0x00,0x31,0x43,0x04};
                [data appendBytes:byte1 length:sizeof(byte1)];
            }else {
                //居中
                [data appendData:[self setAlignment:NSTextAlignmentCenter]];
                Byte byte1[] = {0x1D,0x28,0x6B,0x03,0x00,0x31,0x43,0x04};
                [data appendBytes:byte1 length:sizeof(byte1)];
//                //居左
//                [data appendData:[self setAlignment:NSTextAlignmentLeft]];
//                EscCommand *command = [[EscCommand alloc] init];
//                [command addSetAbsolutePrintPosition:72];
//                [data appendData:[command getCommand]];
//                Byte byte1[] = {0x1D,0x28,0x6B,0x03,0x00,0x31,0x43,0x03};
//                [data appendBytes:byte1 length:sizeof(byte1)];
            }
        }
        
        // 纠错等级 48~51
        Byte byte2[] = {0x1D,0x28,0x6B,0x03,0x00,0x31,0x45,0x51};
        [data appendBytes:byte2 length:sizeof(byte2)];
        
        // 二维码数据存储到符号存储区
        NSInteger kLength = value.length + 3;
        NSInteger pL = kLength % 256;
        NSInteger pH = kLength / 256;
        Byte byte3[] = {0x1D,0x28,0x6B,pL,pH,0x31,0x50,48};
        [data appendBytes:byte3 length:sizeof(byte3)];
        NSData *infoData = [value dataUsingEncoding:NSUTF8StringEncoding];
        [data appendData:infoData];
        
        // 打印之前存储的二维码信息
        Byte byte4[] = {0x1D,0x28,0x6B,0x03,0x00,0x31,0x51,48};
        [data appendBytes:byte4 length:sizeof(byte4)];
        // 打印文字
        if ([kPrint containsString:@"PrinterLE_"]) {
            [data appendData:[self lineFeed]];
        }
        [data appendData:[self printCenterText2:key font:(PrinterPrintTextFontSmall)]];
        // 换行
        [data appendData:[self lineFeed]];
    }
    
    return data;
}

- (NSData *)printPartingLine:(NSInteger)originX {
    
    SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
    NSInteger printerByteWidth = 48;
    if ([overallSetting.printSize.value isEqualToString:@"0"] && [SAValueManger shareInStance].oldPrint != YES) {
        printerByteWidth = 34;
    }
    
    NSString *partingLine = @"-";
    NSInteger partingLineLength = printerByteWidth-originX;
    for (NSInteger i = 0; i < partingLineLength-1; i++) {
        partingLine = [NSString stringWithFormat:@"%@-",partingLine];
    }
    NSData *data = [self printTextInfoArray:@[@{partingLine:[NSString stringWithFormat:@"%zd",originX]}]];
    return data;
}

@end
